package com.primaryedu.ui.repair;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.primaryedu.R;
import com.primaryedu.adapter.RepairDetailsAdapter;
import com.primaryedu.bean.FunctionBean;
import com.primaryedu.bean.RepairBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.CustomDialog;
import com.primaryedu.picture.PicturePreviewActivity;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.DragGridViewOlder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thomas on 2018/3/5.
 */

public class RepairApproveActivity extends BaseActivity implements View.OnClickListener {
    private DragGridViewOlder gridView;
    RepairDetailsAdapter adapter;
    private List<FunctionBean> functionList;

    private TextView text_name, text_phone, text_grade;
    private TextView text_goods, text_date, text_content;
    private ImageView imageStatus;

    private TextView text_department, text_classly;
    private RadioGroup radioGroup;
    private RadioButton rb_pending_repair;
    private RadioButton rb_processing_repair;
    private RadioButton rb_processed_repair;
    private int opinionStatus = 1;
    private EditText edit_repairapproveopinion;
    private CustomDialog.Builder ibuilder;
    private Button bt_sumit_repairapprove;
    private ImageView videoCover;
    private ImageView iv_video_play;
    private RepairBean repairBean;
    private TextView tv_approve_people;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_repair_approve);

        init();
    }

    private void init() {
        ((TextView) this.findViewById(R.id.title)).setText("报修详情");
        findViewById(R.id.back).setOnClickListener(this);
        gridView = (DragGridViewOlder) this.findViewById(R.id.gridView);
        text_name = (TextView) this.findViewById(R.id.text_name);
        text_phone = (TextView) this.findViewById(R.id.text_phone);
        text_grade = (TextView) this.findViewById(R.id.text_grade);
        text_goods = (TextView) this.findViewById(R.id.text_goods);
        text_date = (TextView) this.findViewById(R.id.text_date);
        text_content = (TextView) this.findViewById(R.id.text_content);
        imageStatus = (ImageView) this.findViewById(R.id.imageStatus);
        text_department = (TextView) this.findViewById(R.id.text_department);
        videoCover = (ImageView) findViewById(R.id.video_cover_repair_approve);
        iv_video_play = (ImageView) findViewById(R.id.iv_video_play_repair_approve);
        tv_approve_people = (TextView) findViewById(R.id.tv_approve_people);
        //审批意见
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RepairApproveActivity.OpinionRadioButtonListener());//给RadioGroup绑定监视器
        //未处理
        rb_pending_repair = (RadioButton) findViewById(R.id.rb_pending_repair);
        //处理中
        rb_processing_repair = (RadioButton) findViewById(R.id.rb_processing_repair);
        //已处理
        rb_processed_repair = (RadioButton) findViewById(R.id.rb_processed_repair);
        //报修处理结果输入框
        edit_repairapproveopinion = (EditText) findViewById(R.id.edit_repairapproveopinion);

        //提交
        bt_sumit_repairapprove = (Button) findViewById(R.id.bt_sumit_repairapprove);
        findViewById(R.id.bt_sumit_repairapprove).setOnClickListener(this);
        setData();
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_repair_approve;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    private void setData() {
        repairBean = GlobalData.repairBean;
//		text_name.setText("姓名:"+repairBean.getUsername());
        if (repairBean.getTel() == null) {
            text_phone.setText("联系电话:");
        } else {
            text_phone.setText("联系电话:" + repairBean.getTel());
        }
        if (repairBean.getClassname() == null) {
            text_grade.setText("地点:");
        } else {
            text_grade.setText("地点:" + repairBean.getClassname());
        }
        if (repairBean.getGoodsname() == null) {
            text_goods.setText("报修物品:");
        } else {
            text_goods.setText("报修物品:" + repairBean.getGoodsname());
        }
        if (repairBean.getCreateDate() == null) {
            text_date.setText("报修时间:");
        } else {
            text_date.setText("报修时间:" + repairBean.getCreateDate());
        }
        if (repairBean.getContent() == null) {
            text_content.setText("描述:");
        } else {
            text_content.setText("描述:" + repairBean.getContent());
        }
        if (repairBean.getWorker().equals("")) {
            tv_approve_people.setText("审批人：" + GlobalData.getUsername(this));
        } else {
            tv_approve_people.setText("审批人：" + repairBean.getWorker());
        }
//		text_department.setText("报修部门:"+repairBean.getOffice());
//		text_classly.setText("物品种类:"+repairBean.getClassify());

        Log.i("yy", "setData: userid========" + GlobalData.getUserId(this));

        if (!TextUtils.isEmpty(repairBean.getStatus())) {
            if (repairBean.getStatus().equals("1")) {
                imageStatus.setBackgroundResource(R.drawable.icon_to_manage);
                rb_pending_repair.setChecked(true);
            } else if (repairBean.getStatus().equals("2")) {
                imageStatus.setBackgroundResource(R.drawable.icon_manageing);
                rb_processing_repair.setChecked(true);
            } else {
                imageStatus.setBackgroundResource(R.drawable.icon_managed);
                rb_processed_repair.setChecked(true);
            }
        }

        if (repairBean.getVideo().equals("")) {
            initGridData();
        } else {
            videoCover.setVisibility(View.VISIBLE);
            iv_video_play.setVisibility(View.VISIBLE);
            videoCover.setOnClickListener(this);
            MediaMetadataRetriever media = new MediaMetadataRetriever();

            media.setDataSource(Contants.course_api + repairBean.getVideo(), new HashMap<String, String>());
            Bitmap frameAtTime = media.getFrameAtTime();
            videoCover.setImageBitmap(frameAtTime);
        }

        edit_repairapproveopinion.setText(repairBean.getResult());
    }

    private void initGridData() {
        RepairBean repairBean = GlobalData.repairBean;
        functionList = new ArrayList<>();
        FunctionBean bean = new FunctionBean();
        bean.setPicUrl(repairBean.getPicUrl1());
        functionList.add(bean);

        FunctionBean bean2 = new FunctionBean();
        bean2.setPicUrl(repairBean.getPicUrl2());
        functionList.add(bean2);

        FunctionBean bean3 = new FunctionBean();
        bean3.setPicUrl(repairBean.getPicUrl3());
        functionList.add(bean3);

        System.out.println("functionList" + functionList.toString());
        gridView.setItems(functionList);
        adapter = new RepairDetailsAdapter(this, functionList);
        gridView.setAdapter(adapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Intent intent = new Intent(RepairApproveActivity.this, PicturePreviewActivity.class);
                intent.putExtra("url", functionList.get(position).getPicUrl());
                startActivity(intent);
            }
        });
    }

    private void requestRepairApprovelist() {
        showLoading("提交中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.approveRepair,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=repairapprove=" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("审批成功");
                                Intent intent = getIntent();
                                setResult(3, intent);
                                finish();
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");
                                System.out.println("leaveLists==" + listStr);
                            } else if (result == 0) {
                                showToast("审批失败，请重新审批！");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("提交失败，请重新提交");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", repairBean.getId());
                map.put("status", String.valueOf(opinionStatus));
                map.put("wid", GlobalData.getUserId(RepairApproveActivity.this));
                map.put("worker", GlobalData.getUsername(getApplicationContext()));
                map.put("result", edit_repairapproveopinion.getText().toString());
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bt_sumit_repairapprove:
                if (Utils.isBlank(edit_repairapproveopinion.getText().toString())) {
                    showhintDialog("提示", "请输入您的审批意见！");
                } else {
                    showApplyleavetrue();
                }
                break;
            case R.id.video_cover_repair_approve:
                intent = new Intent(RepairApproveActivity.this, RepairVideoActivity.class);
                intent.putExtra("video_path", Contants.course_api + repairBean.getVideo());
                startActivity(intent);
            default:
                break;
        }
    }

    private void showApplyleavetrue() {
        ibuilder = new CustomDialog.Builder(RepairApproveActivity.this);
        ibuilder.setTitle("报修");
        ibuilder.setMessage("确定审批吗？");
        ibuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        ibuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                requestRepairApprovelist();
            }
        });

        Dialog dialog = ibuilder.create();
        dialog.show();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.width = (int) (d.getWidth() * 0.8);    //宽度设置为屏幕的0.9
        dialog.getWindow().setAttributes(p);     //设置生效
    }

    class OpinionRadioButtonListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 选中状态改变时被触发
            switch (checkedId) {
                case R.id.rb_pending_repair:
                    // 当用户选择未处理时
                    opinionStatus = 1;
//					showToast("opinionStatus=1");
                    break;
                case R.id.rb_processing_repair:
                    // 当用户选择处理中时
                    opinionStatus = 2;
//					showToast("opinionStatus=2");
                    break;
                case R.id.rb_processed_repair:
                    // 当用户选择已处理时
                    opinionStatus = 3;
//					showToast("opinionStatus=3");
                    break;
            }
        }
    }
}
